#include <iostream>
#include <thread>
#include <mutex>

int count = 0;
std::mutex count_mutex;

/*
   会进行判断等待，等待是丢失循环次数
   无法轻易预测这段代码的结果，因为两个线程的调度都由操作系统控制
*/

void producer(void)
{
   for(int i = 0;i < 10; i++)
   {
      count_mutex.lock();
      if(!count)
          count = i;
      count_mutex.unlock(); 
      std::this_thread::sleep_for(std::chrono::microseconds(1));
   }
}

void consumer(void)
{
   for(int i = 0;i < 10;i++)
   {
      count_mutex.lock();
      if(count)
      {
         std::cout << count << std::endl;
         count = 0;
      }
      count_mutex.unlock();
      std::this_thread::sleep_for(std::chrono::microseconds(1));
   }
}


int main()
{
   std::thread t1(producer);
   std::thread t2(consumer);

   t1.join();
   t2.join();

}
